package com.uama.audio.voice;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.SpeechRecognizer;
import com.uama.audio.R;
import com.uama.audio.util.SpeechManager;
import com.uama.audio.util.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cafe.adriel.androidaudioconverter.callback.IConvertCallback;

public class VoiceAssistantActivity extends AppCompatActivity {

    @BindView(R.id.et_desc)
    EditText etDesc;
    @BindView(R.id.btn_speech)
    Button btnSpeech;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.btn_clear_text)
    Button btnClearText;
    @BindView(R.id.btn_play)
    Button btnPlay;
    private SpeechRecognizer mSpeechRecognizer;
    private String mAudioWavPath;
    private static String TAG = VoiceAssistantActivity.class.getSimpleName();
    private RecognizerListener mRecognizerListener;
    private HashMap<String, String> mIatResults = new LinkedHashMap<>();// 用HashMap存储听写结果
    private String descContent = "";
    private MediaPlayer mMediaPlayer;
    private String mAudioDir;
    private String mTargetAudioPath;
    private IConvertCallback mConvertCallback;
    private SpeechManager.SpeechListener mSpeechListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_assistant);
        ButterKnife.bind(this);
        initView();
        initSpeechListener();
        mSpeechRecognizer = SpeechManager.getInstance().getRecognizer();
    }


    @OnClick({R.id.btn_clear_text, R.id.btn_convert, R.id.btn_play, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_clear_text:
                etDesc.setText("");
                descContent = "";
                SpeechManager.getInstance().clearAudio();
                break;
            case R.id.btn_convert:
                SpeechManager.getInstance().convertToMp3(new SpeechManager.ConvertListener() {
                    @Override
                    public void onSuccess(File file) {
                        startPlay(file.getAbsolutePath());
                    }

                    @Override
                    public void onFailed(Exception e) {

                    }
                });
                break;
            case R.id.btn_play:
                break;
            case R.id.btn_commit:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SpeechManager.getInstance().clearAudio();
        mSpeechRecognizer.destroy();
    }

    private void initView() {
        btnSpeech.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startRecord();
                        break;
                    case MotionEvent.ACTION_UP:
                        stopRecord();
                        break;
                }
                return false;
            }
        });
        btnPlay.setVisibility(View.GONE);
    }

    private void stopRecord() {
        btnSpeech.setText("按住说话");
        SpeechManager.getInstance().stopSpeech(mSpeechRecognizer);
    }

    private void startRecord() {
        btnSpeech.setText("松开结束");
        SpeechManager.getInstance().startSpeech(mSpeechRecognizer,mSpeechListener) ;
    }

    private void initSpeechListener(){
        mSpeechListener = new SpeechManager.SpeechListener() {
            @Override
            public void onVolumeChanged(int i, byte[] bytes) {

            }

            @Override
            public void onResult(String result) {
                descContent += result;
                etDesc.setText(descContent);
                etDesc.setSelection(etDesc.getText().length());
            }

            @Override
            public void onError(int code, String error) {
                if (code == 14002) {
                    ToastUtil.showTips(error + "\n请确认是否已开通翻译功能");
                } else if (code == 10118) {
                    ToastUtil.showTips("您没有说话,请确认录音权限是否打开");
                } else {
                    ToastUtil.showTips(error);
                }
                Log.e(TAG, "onError:  " + error);
            }
        };
    }

    private void startPlay(String path) {
        if (!new File(path).exists()) {
            Log.e(TAG, "file is not exist: " + path);
            return;
        }
        if (mMediaPlayer != null) {
            stopPlayer();
        }

        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    stopPlayer();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // 停止播放录音
    public void stopPlayer() {
        if (mMediaPlayer == null) {
            return;
        }
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }


}
